package com.ruoyi.program.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import com.alipay.api.AlipayConfig; // 假设 AlipayConfig 来自支付宝 SDK，添加导入语句
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.ruoyi.program.domain.AlipayUser;
import com.ruoyi.program.service.IAlipayUserService; // 假设有 UserService 用于操作数据库
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.ruoyi.common.annotation.Anonymous;
// 在类的顶部添加@Value注解导入
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity; // 添加缺少的导入语句
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Anonymous
@RestController
public class LoginController {

  @Autowired
  private IAlipayUserService alipayUserService; // 注入 UserService

  // 添加@Value注解读取微信小程序配置
  @Value("${wechat.appid}")
  private String appId;

  @Value("${wechat.secret}")
  private String appSecret;

  // 支付宝小程序登录接口
  @PostMapping("/alipayapi/api/login")
  public Map<String, Object> login(@RequestBody Map<String, String> requestBody) {
    Map<String, Object> result = new HashMap<>();

    try {
      // 从请求体中获取 authCode
      String authCode = requestBody.get("authCode");
      // 获取支付宝配置
      AlipayConfig alipayConfig = getAlipayConfig();
      // 创建 AlipayClient 实例
      AlipayClient alipayClient = new DefaultAlipayClient(
          alipayConfig.getServerUrl(),
          alipayConfig.getAppId(),
          alipayConfig.getPrivateKey(),
          alipayConfig.getFormat(),
          alipayConfig.getCharset(),
          alipayConfig.getAlipayPublicKey(),
          alipayConfig.getSignType());

      // 创建请求对象
      AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
      request.setCode(authCode); // 设置 authCode
      request.setGrantType("authorization_code"); // 固定值

      // 发起请求并获取响应
      AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
      System.out.println("response*************====================: " + response.getBody());
      // 检查响应是否成功
      if (response.isSuccess()) {
        // 提取用户信息
        String userId = response.getUserId();
        String openId = response.getAlipayUserId();
        String accessToken = response.getAccessToken();
        String expiresIn = response.getExpiresIn();
        String refreshToken = response.getRefreshToken();
        Date authStartDate = response.getAuthStart();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String authStart = authStartDate != null ? sdf.format(authStartDate) : null;

        AlipayUser user = new AlipayUser();
        user.setUserId(userId);
        user.setOpenId(openId);
        user.setAccessToken(accessToken);
        user.setRefreshToken(refreshToken);
        user.setAuthStart(authStart);
        user.setAuthCode(authCode);
        user.setExpiresIn(expiresIn);
        user.setReExpiresIn(expiresIn);

        // try {
        // // 尝试将 expiresIn 字符串转换为 Integer 类型
        // Integer expiresInInt = Integer.parseInt(expiresIn);
        // user.setExpiresIn(expiresInInt);
        // } catch (NumberFormatException e) {
        // // 处理转换失败的情况，可根据实际需求调整日志记录或错误处理逻辑
        // System.err.println("Failed to convert expiresIn to Integer: " +
        // e.getMessage());
        // }
        // try {
        // // 尝试将 reExpiresIn 字符串转换为 Integer 类型
        // Integer reExpiresInInt = Integer.parseInt(reExpiresIn);
        // user.setReExpiresIn(reExpiresInInt);
        // } catch (NumberFormatException e) {
        // // 处理转换失败的情况，可根据实际需求调整日志记录或错误处理逻辑
        // System.err.println("Failed to convert reExpiresIn to Integer: " +
        // e.getMessage());
        // }
        // System.out.println("user" + user);

        // 检查用户是否已经存在
        // AlipayUser existingUser = alipayUserService.selectAlipayUserByUserId(userId);
        // System.out.println("existingUser: " + existingUser);
        // if (existingUser != null) {
        // // 用户已存在，直接返回用户信息
        // result.put("code", 200);
        // result.put("message", "用户已登录");
        // result.put("userId", existingUser.getUserId());
        // return result;
        // } else {
        // // 保存用户信息到数据库
        alipayUserService.insertAlipayUser(user);
        // 封装结果 返回用户id
        result.put("code", 200);
        result.put("message", "登录成功");
        result.put("userId", user.getUserId());
        // }
      } else {
        // 处理失败情况
        result.put("code", 500);
        result.put("message", "登录失败：" + response.getSubMsg());
        return result;
      }
    } catch (Exception e) {
      // 捕获异常并返回错误信息
      result.put("code", 500);
      result.put("message", "服务器内部错误：" + e.getMessage());
    }

    return result;
  }

  // 微信小程序登录接口
  @PostMapping("/wechatapi/api/login")
  public Map<String, Object> weChatLogin(@RequestBody Map<String, String> requestBody) {
    Map<String, Object> result = new HashMap<>();
    try {
      // 从请求体中获取 code
      String code = requestBody.get("code");

      if (code == null || code.isEmpty()) {
        result.put("code", 400);
        result.put("message", "code不能为空");
        return result;
      }

      // 直接使用@Value注入的配置，无需硬编码
      // 构造微信登录API请求URL
      String url = String.format(
          "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
          appId, appSecret, code);

      // 发送HTTP请求到微信服务器
      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

      // 解析微信返回的JSON响应
      // 假设使用 FastJSON 解析，需确保项目中已添加 FastJSON 依赖
      JSONObject jsonResponse = JSON.parseObject(response.getBody());

      // 检查是否包含错误信息
      if (jsonResponse.containsKey("errcode")) {
        int errCode = jsonResponse.getIntValue("errcode");
        if (errCode != 0) {
          result.put("code", 500);
          result.put("message", "微信登录失败：" + jsonResponse.getString("errmsg"));
          return result;
        }
      }

      // 登录成功，获取openid等信息
      String openid = jsonResponse.getString("openid");
      String sessionKey = jsonResponse.getString("session_key");
      // String unionid = jsonResponse.getString("unionid");

      // TODO: 这里应该实现自己的用户登录逻辑，例如：
      // 1. 根据openid查询或创建用户
      // 2. 生成并返回自定义的登录态token
      // 把openid和sessionKey 保存用户信息到数据库
      AlipayUser user = new AlipayUser();
      user.setUserId(openid);
      // 由于 AlipayUser 类没有 setSessionKey 方法，推测应使用合适的方法来保存 sessionKey
      // 这里假设使用 setOpenId 保存 openid，使用 setAccessToken 保存 sessionKey 作为示例，实际需根据业务调整
      user.setAccessToken(sessionKey);
      user.setUserType(1); //1:微信用户
      
      // alipayUserService.insertAlipayUser(user);

      result.put("code", 200);
      result.put("message", "登录成功");
      // 使用HashMap替代Map.of()，确保Java 8兼容性
      Map<String, String> dataMap = new HashMap<>();
      dataMap.put("userId", openid);
      dataMap.put("session_key", sessionKey);
      // dataMap.put("unionid", unionid);
      result.put("data", dataMap); // 返回数据

    } catch (Exception e) {
      // 捕获异常并返回错误信息
      result.put("code", 500);
      result.put("message", "服务器内部错误：" + e.getMessage());
    }

    return result;
  }

  private static AlipayConfig getAlipayConfig() {
    String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQClchY2I8m+8HvDDeEJzRntvsXyEOI/ukcmfnvXQbD+0i9usktNiaRYRwFPmpLBoXplbqNa9cBeDk0/XfePJjV4H1su5yTS8+twZW2LwD1tIFkIfpHQhj0tiOHaJoOrkvpkCiR7Y9wOPRUHkwqjooKzCuuMy/5J7bhMozqRVETk8Mqx92qFUrf5Ix3mt/0el8H+KzBOmSCY6un7qOgBSbmqoGCFswPaYNrfiwYBxKeHY2BGytj7OT0HHHPhgIgDkkiIRxiF8+2/ZVZdFContdISfHdY4+cyohz1pLQ5DhZURQSh9dyAa0cPTPnNLq9wbGMDhvSsx6lzNCoSk7YixfpTAgMBAAECggEAL34hjCcX2dz02hhY2lRrNglGj2dzWzHhDNbQPAmagnvZq+A4p6h0afbwFGbd7AGrvgRVll3ne9iFKkSSNSCVxsbRiRRHSNtGYbxsBusHdxULGdojh4WReEnL87CMqasGf8M9l8IhwGCecc8vBaw38qeW2JMSiyxXdICC5ocXQ9S3Q2bkd7nNa+ssPjhJv3gFLTufOsF0LAWAB5REwjxW76WGkafw/6hQJ71GKQhrweeU52looDmnqasBuvwyoMEAHNALk6Bzn79YQ5EupM1mKTIOIUcFq9Zu9YAci92QHk6Ohsfb27XaVCY1wawB3wH3jWUtBWndFQn++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bUI3FPl8Wlbp4aJGZmhUKbZHK5Qg/akk+gb8Wf4hC/sZ3qTtGkqFbhCZiRz4HghDfRvQJ3KoU/OLThQD30MlzUVb7rF31aaBloGeCAfmPPAqCrjQM/iWb/im3ArRz6zGrQoOy5KxjDBV0me/Fiq6uD5EApgpYWTzCpbwmB3HHPPB8xRLszV3GMncSx7uLk6iavggN2Cd4P5TwIDAQAB";
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
    alipayConfig.setAppId("2021005162626299");
    alipayConfig.setPrivateKey(privateKey);
    alipayConfig.setFormat("json");
    alipayConfig.setAlipayPublicKey(alipayPublicKey);
    alipayConfig.setCharset("UTF-8");
    alipayConfig.setSignType("RSA2");
    return alipayConfig;
  }
}